package com.chzc.fm.duotin.ui.channel;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.bean.channel.Play;
import com.chzc.fm.duotin.bean.channel.Rank;
import com.chzc.fm.duotin.ui.channel.event.PlayEvent;
import com.chzc.fm.duotin.utils.Blur;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.GlobalParam;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.ImageUtil;
import com.chzc.fm.duotin.utils.LogUtil;
import com.chzc.fm.duotin.widget.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/30.
 */
public class LivePlayActivity extends AppCompatActivity implements View.OnClickListener,MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener {

    private TextView tvtitle,tvtype;
    private ImageView ivback,ivtracklist,ivplay,ivbg,ivloading;
    private CircleImageView circleImageView;
    public  List<Play> playList = new ArrayList<>();

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private String mp3Url;

    private ObjectAnimator anima;

    private String dataid;


    private static final int  REQUEST_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liveplay);

        initViews();

        initDatas();

    }

    public void initViews()
    {
        tvtitle = (TextView) findViewById(R.id.live_title_tv);
        tvtype = (TextView) findViewById(R.id.live_type_tv);
        ivback = (ImageView) findViewById(R.id.live_back_iv);
        ivtracklist = (ImageView) findViewById(R.id.live_tracklist_iv);
        ivplay = (ImageView) findViewById(R.id.live_play_iv);
        ivbg = (ImageView) findViewById(R.id.live_bg_iv);
        circleImageView = (CircleImageView) findViewById(R.id.live_main_civ);
        ivloading = (ImageView) findViewById(R.id.live_loading_iv);

        ivback.setOnClickListener(this);
        ivtracklist.setOnClickListener(this);
        ivplay.setOnClickListener(this);

        mediaPlayer.setOnPreparedListener(this);  // 准备监听
        mediaPlayer.setOnCompletionListener(this); // 播放完毕监听

    }


    public void initDatas()
    {
        //注册订阅者
        EventBus.getDefault().register(this);

        Rank rankitem = (Rank) getIntent().getSerializableExtra("rankitem");
        dataid = rankitem.getId()+"";

        getLivePlay(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {

                try {

                    LogUtil.w("开始解析数据");
                    JSONObject root = new JSONObject(object.toString());
                    String error_msg = root.getString("error_msg");
                    if("SUCCESS".equals(error_msg))
                    {
                        LogUtil.w("解析成功");

                        JSONObject data = root.getJSONObject("data");
                        JSONArray datalist = data.getJSONArray("data_list");
                        playList = Play.arrayPlayFromData(datalist.toString());

                        Play play = playList.get(0);
                        showblurimag(0);
                        ImageLoader.getInstance().displayImage(play.getImage_url(),circleImageView, ImageUtil.getDefaultOptions());
                        tvtitle.setText(play.getTitle());
                        tvtitle.requestFocus();
                        mp3Url = play.getHref();

                        playByUrl(mp3Url);


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    public void showblurimag(int position)
    {
        Play play = playList.get(position);
        final String imgurl = play.getImage_url();

        DuotinTask.IDownloadListener downloadListener = new DuotinTask.IDownloadListener() {
            @Override
            public void upgradeProgress(float progress) {

            }

            @Override
            public void onComplete(File file) {

                final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

                final Bitmap blurbitmap = Blur.fastblur(LivePlayActivity.this,bitmap,15);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                       ivbg.setImageBitmap(blurbitmap);
                    }
                });


            }

            @Override
            public void onFail(String msg) {

            }

            @Override
            public void start() {

            }
        };

        new DuotinTask(new DuotinTask.IDownloadRequest() {
            @Override
            public Object doRequest(DuotinTask.IDownloadListener listener) {
                return HttpUtil.download(imgurl, FileUtils.DIR_IMAGE,FileUtils.getFileNameByHashCode(imgurl),listener);
            }
        },downloadListener).execute();
    }

    /**
     * 获取播放列表数据
     * @param callback
     */
    public void getLivePlay(DuotinTask.IRequestCallback callback)
    {
        DuotinTask.IRequest request = new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {
                return HttpUtil.doGet(GlobalParam.URL_LIVEPLAY_HEAD + dataid + GlobalParam.URL_LIVEPLAY_TAIL);
            }
        };

        new DuotinTask(request,callback).execute();
    }


    /**
     * 获取返回数据
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.live_back_iv:
                finish();
                break;
            case R.id.live_tracklist_iv:
                LogUtil.w("发送数据给列表页面");
                Intent intent = new Intent(LivePlayActivity.this,PlayTrackListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("playlist", (Serializable) playList);
                intent.putExtras(bundle);
                startActivityForResult(intent,REQUEST_CODE);
                overridePendingTransition(R.anim.activity_open,0);
                break;
            case R.id.live_play_iv:
                if(mediaPlayer.isPlaying())
                {
                    mediaPlayer.pause();
                    ivplay.setImageResource(R.drawable.ic_track_paused_nor);
                    anima.pause();

                }else
                {
                    mediaPlayer.start();
                    ivplay.setImageResource(R.drawable.ic_track_playing_nor);
                    anima.resume();

                }
                break;

        }
    }


    /**
     * 通过mp3url下载播放文件
     * @param mp3url
     */
    public void playByUrl(final String mp3url)
    {
        //ivloading.setVisibility(View.VISIBLE);

        /*Animation animation = AnimationUtils.loadAnimation(LivePlayActivity.this,R.anim.foreverrotate);
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);*/

        anima = ObjectAnimator.ofFloat(circleImageView,"rotation",0,360);
        anima.setDuration(10000);
        anima.setRepeatCount(-1);
        anima.setInterpolator(new LinearInterpolator());
        anima.setRepeatMode(ObjectAnimator.RESTART);
        anima.start();

        Animation loadanimation = AnimationUtils.loadAnimation(LivePlayActivity.this,R.anim.foreverrotate);
        loadanimation.setInterpolator(new LinearInterpolator());
        ivloading.startAnimation(loadanimation);



        new Thread(new Runnable() {
            @Override
            public void run() {

                HttpUtil.download(mp3url, FileUtils.DIR_MP3, FileUtils.getFileNameByHashCode(mp3url), new DuotinTask.IDownloadListener() {
                    @Override
                    public void upgradeProgress(float progress) {

                    }

                    @Override
                    public void onComplete(File file) {

                        play(file);
                    }

                    @Override
                    public void onFail(String msg) {

                    }

                    @Override
                    public void start() {

                    }
                });

            }
        }).start();
    }

    /**
     * 播放
     */
    public void play(File file)
    {
        Uri uri = Uri.fromFile(file);

        //重置
        mediaPlayer.reset();

        try {
            //设置播放路径
            mediaPlayer.setDataSource(this,uri);
            //缓冲
            mediaPlayer.prepare();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 暂停
     */
    public void pause()
    {
        if (mediaPlayer.isPlaying())
        {
            mediaPlayer.pause();
        }
    }

    /**
     * 停止
     */
    public void stop()
    {
        if (mediaPlayer.isPlaying())
        {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }



    /**
     * 下载完成监听
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {

        mp.start();
    }

    /**
     * 准备监听
      * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        ivloading.setVisibility(View.GONE);
        ivloading.clearAnimation();
        ivplay.setImageResource(R.drawable.ic_track_playing_nor);
        mp.start();
    }

    /**
     * 订阅事件
     * 不管发布者的操作是在哪个线程，操作一律放在ＵＩ线程中执行
     * @param event
     */
    @Subscribe
    public void onEventMainThread(PlayEvent event)
    {
        LogUtil.w("onEventMainThread " + event.getMsg() );
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
        mediaPlayer.release();
        mediaPlayer = null;
    }
}
